import { defineStore } from 'pinia'
import axios from 'axios'

export const useProductStore = defineStore('product', {
  state: () => ({
    productList: [],
    loading: false,
    lastUpdateTime: null,
    pagination: {
      current: 1,
      size: 8,
      total: 0
    }
  }),

  actions: {
    async fetchProductList() {
      this.loading = true
      try {
        const response = await axios.get("/getGoods", {
          params: {
            current: this.pagination.current,
            size: this.pagination.size
          },
          headers: {
            Authorization: sessionStorage.getItem("Authorization"),
          }
        })

        console.log('API Response:', response.data)

        if (response.data.status === 200) {
          const { records, total, current, size } = response.data.data
          this.productList = records || []
          this.pagination = {
            current: current || this.pagination.current,
            size: size || this.pagination.size,
            total: total || 0
          }
          this.lastUpdateTime = Date.now()
        } 
      } catch (error) {
        console.error('获取商品列表错误:', error)
      } finally {
        this.loading = false
      }
    },

    async updatePagination(newPagination) {
      this.pagination = {
        ...this.pagination,
        ...newPagination
      }
      await this.fetchProductList()
    },

    async refreshProductList() {
      await this.fetchProductList()
    },

    clearProductList() {
      this.productList = []
      this.lastUpdateTime = null
      this.pagination = {
        current: 1,
        size: 8,
        total: 0
      }
    }
  },

  persist: {
    key: 'product-store',
    storage: localStorage,
    paths: ['productList', 'lastUpdateTime', 'pagination'],
    beforeRestore: () => {
      console.log('从存储中恢复数据')
    },
    afterRestore: () => {
      console.log('数据恢复完成')
    }
  }
})